package com.pac.weixin.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.common.tools.StringTools;
import com.common.util.LogicException;
import com.common.util.MsgKeyContent;
import com.common.util.PropertyUtils;
import com.kuanrf.commons.weixin.api.WxService;
import com.kuanrf.commons.weixin.bean.WxJsapiSignature;
import com.kuanrf.commons.weixin.msg.bean.result.WxOAuth2AccessToken;
import com.pac.questionnaire.QuestionnaireKeyContent;
import com.pac.questionnaire.bean.QuestionnaireBean;
import com.pac.questionnaire.service.QuestionnaireDiagnosisService;
import com.pac.questionnaire.service.QuestionnaireService;
import com.pac.user.bean.UserDetailBean;
import com.pac.user.service.UserDetailService;
import com.pac.weixin.WeiXinKeyContent;
import com.pac.weixin.service.WeiXinService;

/**
 * 问卷微信入口
 * 
 * @author lujun.chen
 * @version [版本号, 2015年3月2日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@Scope("prototype")
@RequestMapping("/weixin/qusetionnaire")
public class WxQusetionnaireController {

	private static Logger logger = Logger
			.getLogger(WxQusetionnaireController.class);

	@Autowired
	private QuestionnaireService questionnaireService;

	@Autowired
	private QuestionnaireDiagnosisService questionnaireDiagnosisService;

	@Autowired
	private WxService wxMpService;

	@Autowired
	private WeiXinService weiXinService;

	@Autowired
	private UserDetailService userDetailService;

	/**
	 * 按照用户ID查询问卷列表
	 * 
	 * @param userId
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/query")
	@ResponseBody
	public List<QuestionnaireBean> queryQuestionnaire(String userId) {

		// 查询发布状态的问卷
		QuestionnaireBean questionnaireBean = new QuestionnaireBean();
		questionnaireBean.setUserId(userId);
		questionnaireBean
				.setState(QuestionnaireKeyContent.QUESTIONNAIRE_STATE_RELEASE);
		List<QuestionnaireBean> questionnaireList = questionnaireService
				.queryQuestionnaire(questionnaireBean);

		return questionnaireList;
	}

	/**
	 * 按问题ID查询问卷，进入问卷页面
	 * 
	 * @param questionnaireId
	 * @param back
	 *            是否需要返回 true 需要返回；false 不需要返回
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/goto")
	public ModelAndView gotoQuetionnairePage(String questionnaireId, String back) {
		// 获取问卷
		QuestionnaireBean questionnaireBeanQ = new QuestionnaireBean();
		questionnaireBeanQ.setId(questionnaireId);
		QuestionnaireBean questionnaireBeanR = questionnaireService
				.findQuestionnaire(questionnaireBeanQ);

		ModelAndView mov = new ModelAndView();
		mov.setViewName("/weixin/questionnaire/questionnaire");
		mov.addObject("questionnaire", questionnaireBeanR);
		mov.addObject("questions", questionnaireBeanR.getQuestions());
		mov.addObject("back", back);
		return mov;
	}

	/**
	 * 提交问卷
	 * 
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/answer")
	@ResponseBody
	public Map<String, Object> answerQuestionnaire(HttpServletRequest request,
			String openId) {
		boolean result = true;
		String msg = "操作成功";
		String diagnosis = "";

		try {

			// 获取传过来的文件
			Map<String, List<MultipartFile>> filesMap = new HashMap<String, List<MultipartFile>>();
			if (request instanceof DefaultMultipartHttpServletRequest) {
				DefaultMultipartHttpServletRequest requestM = (DefaultMultipartHttpServletRequest) request;
				filesMap = requestM.getMultiFileMap();
			}

			// 问卷ID
			String questionnaireId = "";
			Map<String, Object[]> answerMap = new HashMap<String, Object[]>();
			
			Map<String,String> param=new HashMap<String,String>();

			// 解析答案表单
			Map<String, String[]> mapAnswer = request.getParameterMap();
			Set<String> keysets = mapAnswer.keySet();
			for (String key : keysets) {
				String paramV = mapAnswer.get(key)[0];
				if ("questionnaireId".equals(key)) {
					questionnaireId = paramV;
					continue;
				}
				if("batchNo".equals(key))
				{
					param.put("batchNo", paramV);
					continue;
				}

				if (key.startsWith(WeiXinKeyContent.WEIXIN_QUESTION_ANSWER_KEY)) {
					// 问题ID
					String[] answers = mapAnswer.get(key);
					answerMap.put(key, answers);
				}

			}

			Map<String, String> resultMap = questionnaireDiagnosisService
					.answerQuestionnaire(openId, questionnaireId, answerMap,
							filesMap,param);
			diagnosis = resultMap.get("diagnosis");

		} catch (LogicException ex) {
			result = false;
			msg = ex.getMessage();
		} catch (Exception ex) {
			logger.error("提交文件答卷出错，" + ex);
			result = false;
			msg = "系统内部错误";
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, result);
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG, msg);
		map.put("diagnosis", diagnosis);

		return map;
	}

	/**
	 * 答卷单独上传附件
	 * 
	 * @param files
	 *            答卷附件
	 * @param diagnosisId
	 *            答卷ID
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/answer/file/add")
	@ResponseBody
	public Map<String, Object> addDiagnosisFile(
			@RequestParam MultipartFile[] files, String diagnosisId,
			String openid) {

		boolean result = true;
		String msg = "";
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			questionnaireDiagnosisService.addQuestionnaireFile(files,
					diagnosisId, openid);
		} catch (LogicException ex) {
			result = false;
			msg = ex.getMessage();
		} catch (Exception ex) {
			logger.error("答卷单独上传附件出错，" + ex);
			result = false;
			msg = "系统内部错误";
		}

		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, result);
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG, msg);

		return map;
	}

	/**
	 * 检查问卷是否已经被回答过
	 * 
	 * @param openId
	 * @param questionnaireId
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/answered")
	@ResponseBody
	public Map<String, Object> questionnaireIsAnswered(String openId,
			String questionnaireId) {
		boolean result = false;
		String msg = "";

		try {
			result = questionnaireDiagnosisService.questionnairedIsAnswered(
					openId, questionnaireId);
		} catch (Exception ex) {
			logger.error("检查问卷是否已经被回答过陈醋，" + ex);
			result = false;
			msg = "系统内部错误";
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, result);
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG, msg);

		return map;
	}

	/**
	 * 进入问卷M6
	 * 
	 * @param request
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/gotoM6")
	public ModelAndView gotoM6(HttpServletRequest request) {
		ModelAndView mov = new ModelAndView();

		String appId = "";
		String timestamp = "";
		String nonceStr = "";
		String signature = "";
		String openId = "";

		WxOAuth2AccessToken autoToken = null;

		// 检查openId是否已经注册过，没有注册过跳转到注册页面，注册过直接进入问卷M6
		try {
			Map<String, String[]> map = request.getParameterMap();
			String[] wxCodeP = map.get("code");
			if (null != wxCodeP && wxCodeP.length > 0) {
				String wxCode = wxCodeP[0];
				if (!StringTools.isNull(wxCode)) {
					// 通过微信网页授权code换取accessToke和openId
					autoToken = wxMpService.oauth2getAccessToken(wxCode);
					if (null != autoToken) {
						openId = autoToken.getOpenId();
						mov.addObject("openId", openId);
					}
				}
			}

			// 微信页面获取js-sdk授权
			String url = PropertyUtils.getValue("system.domain.url")
					+ "/weixin/qusetionnaire/gotoM6?";
			Set<String> keysets = map.keySet();
			for (String key : keysets) {
				String paramV = map.get(key)[0];
				paramV = URLEncoder.encode(paramV, "UTF-8");
				url += key + "=" + paramV + "&";
				mov.addObject(key, paramV);
			}
			url = url.substring(0, url.length() - 1);
			appId = PropertyUtils.getValue("weixin.appID");
			// 获取微信js授权签名
			WxJsapiSignature jsSign = wxMpService.createJsapiSignature(url);

			timestamp = String.valueOf(jsSign.getTimestamp());
			nonceStr = jsSign.getNoncestr();
			signature = jsSign.getSignature();

			// 检查是否填写明细信息，如果未填写用户明细信息，就进入注册页面
			UserDetailBean userDetail = userDetailService
					.findUserDetailByOpenId(openId);
			if (null == userDetail) {
				try {
					weiXinService.wxUserinfo(autoToken);
				} catch (Exception ex) {
					logger.error("获取微信用户信息出错，" + ex);
				}
				mov.setViewName("/weixin/register/register");
				mov.addObject("comefrom", "M6");
			} else {
				// 进入问卷M6
				mov.setViewName("/weixin/questionnaire/questionnaire53");
			}
			mov.addObject("openId", openId);
		} catch (Exception ex) {
			logger.error("进入问卷M6页面出错，" + ex);
		}

		mov.addObject("appId", appId);
		mov.addObject("timestamp", timestamp);
		mov.addObject("nonceStr", nonceStr);
		mov.addObject("signature", signature);
		return mov;
	}

	/**
	 * 页面跳转
	 * 
	 * @param pageName
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/gotoPage")
	public ModelAndView gotoPage(HttpServletRequest request, String pageName,
			String qusetionnaireId) {
		ModelAndView mov = new ModelAndView();
		mov.setViewName("/weixin/questionnaire/" + pageName);

		String appId = "";
		String timestamp = "";
		String nonceStr = "";
		String signature = "";

		try {
			Map<String, String[]> map = request.getParameterMap();
			String[] wxCodeP = map.get("code");
			if (null != wxCodeP && wxCodeP.length > 0) {
				String wxCode = wxCodeP[0];
				if (!StringTools.isNull(wxCode)) {
					// 通过微信网页授权code换取accessToke和openId
					WxOAuth2AccessToken autoToken = wxMpService
							.oauth2getAccessToken(wxCode);
					if (null != autoToken) {
						String openId = autoToken.getOpenId();
						mov.addObject("openId", openId);
					}
				}
			}

			// 微信页面获取js-sdk授权
			String url = PropertyUtils.getValue("system.domain.url")
					+ "/weixin/qusetionnaire/gotoPage?";
			Set<String> keysets = map.keySet();
			for (String key : keysets) {
				String paramV = map.get(key)[0];
				paramV = URLEncoder.encode(paramV, "UTF-8");
				url += key + "=" + paramV + "&";
				mov.addObject(key, paramV);
			}
			url = url.substring(0, url.length() - 1);
			appId = PropertyUtils.getValue("weixin.appID");
			// 获取微信js授权签名
			WxJsapiSignature jsSign = wxMpService.createJsapiSignature(url);

			timestamp = String.valueOf(jsSign.getTimestamp());
			nonceStr = jsSign.getNoncestr();
			signature = jsSign.getSignature();

		} catch (Exception ex) {
			logger.error("进入微信问卷页面出错，" + ex);
		}

		// 通用问卷模板
		if ("questionnaire".equals(pageName)) {

			QuestionnaireBean questionnaireBeanQ = new QuestionnaireBean();
			questionnaireBeanQ.setId(qusetionnaireId);
			QuestionnaireBean questionnaireBeanR = questionnaireService
					.findQuestionnaire(questionnaireBeanQ);
			if (null != questionnaireBeanR) {
				mov.addObject("questionnaire", questionnaireBeanR);
				mov.addObject("questions", questionnaireBeanR.getQuestions());
			}
		}

		mov.addObject("appId", appId);
		mov.addObject("timestamp", timestamp);
		mov.addObject("nonceStr", nonceStr);
		mov.addObject("signature", signature);

		return mov;
	}

}
